// pages/chatList/chatlist.js
import { API, rootPath } from "../../utils/const";
import { CreateHeader, getRequest } from "../../utils/request";
Page({

  /**
   * Page initial data
   */
  data: {
    chatTargets: [],
  },

  goToChat(e) {
    const item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: `/pages/chatPage/chatpage?id=${item.id}&name=${item.name}&role=${item.role}`,
    });
  },

  /**
   * Lifecycle function--Called when page load
   */
  onLoad(options) {
    this.fetchData()
  },
  fetchData: function () {
    const that = this;
    userRole = wx.getStorageSync('loginType');
    let url = '';
    if (userRole === 'patient') {
      url = API.getDoctorList;
    }
    else {
      url = API.getPatientList;
    }

    let header = {};
    let token = wx.getStorageSync('token');
    let userId = wx.getStorageSync('LoginId');
    let userRole = wx.getStorageSync('loginType');
    header['authorization'] = "Bearer " + token;
    console.log(`Calling ${url}  with ${userRole} - ${userId} ... `);
    let chatTargets = that.data.chatTargets;
    getRequest(url).then(res => {
      if (userRole === 'doctor') {
        res.forEach(element => {
          let chatMate = {
            id: element.patientId,
            name: element.patientName,
            role: 'patient'
          };
          chatTargets.push(chatMate);
        });
      }
      else if (userRole === 'patient') {
        res.forEach(element => {
          let chatMate = {
            id: element.doctorId,
            name: element.doctorName,
            role: 'doctor'
          };
          chatTargets.push(chatMate);
        });
      }
      
      that.setData({
        chatTargets: chatTargets
      });
    });
  },
  /**
   * Lifecycle function--Called when page is initially rendered
   */
  onReady() {

  },

  /**
   * Lifecycle function--Called when page show
   */
  onShow() {

  },

  /**
   * Lifecycle function--Called when page hide
   */
  onHide() {

  },

  /**
   * Lifecycle function--Called when page unload
   */
  onUnload() {

  },

  /**
   * Page event handler function--Called when user drop down
   */
  onPullDownRefresh() {

  },

  /**
   * Called when page reach bottom
   */
  onReachBottom() {

  },

  /**
   * Called when user click on the top right corner to share
   */
  onShareAppMessage() {

  }
})